package org.etcsoft.examples.genealogy.listener;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LayoutManager;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.draw2d.UpdateManager;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;

public class FigureMover implements MouseListener, MouseMotionListener {
    private final IFigure figure;
    private Point location;

    public FigureMover(IFigure figure) {
        this.figure = figure;
        figure.addMouseListener(this);
        figure.addMouseMotionListener(this);
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        if (this.location == null) {
            return;
        }
        Point newLocation = me.getLocation();
        if (newLocation == null) {
            return;
        }
        Dimension offset = newLocation.getDifference(this.location);
        if (offset.width == 0 && offset.height == 0) {
            return;
        }
        this.location = newLocation;

        UpdateManager updateMgr = this.figure.getUpdateManager();
        LayoutManager layoutMgr = this.figure.getParent().getLayoutManager();
        Rectangle bounds = this.figure.getBounds();
        updateMgr.addDirtyRegion(this.figure.getParent(), bounds);
        bounds = bounds.getCopy().translate(offset.width, offset.height);
        layoutMgr.setConstraint(this.figure, bounds);
        this.figure.translate(offset.width, offset.height);
        updateMgr.addDirtyRegion(this.figure.getParent(), bounds);

        me.consume();
    }

    @Override
    public void mouseEntered(MouseEvent me) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent me) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseHover(MouseEvent me) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseMoved(MouseEvent me) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent me) {
        this.location = me.getLocation();
        me.consume();
    }

    @Override
    public void mouseReleased(MouseEvent me) {
        if (this.location == null) {
            return;
        }
        this.location = null;
        me.consume();
    }

    @Override
    public void mouseDoubleClicked(MouseEvent me) {
        // TODO Auto-generated method stub

    }

}
